package com.atguigu.tingshu.account.listener;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * title:
 * author: zgl
 * date: 2024/2/27
 * description：
 */
@Component
public class UserAccountListener {
    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private RechargeInfoService rechargeInfoService;

    //初始化账户
    @KafkaListener(topics = KafkaConstant.QUEUE_USER_REGISTER)
    public void accountConsumer(String userId, Acknowledgment ack) {
        if (StringUtils.isBlank(userId)) {
            ack.acknowledge();
            return;
        }
        userAccountService.saveUserAccount(Long.valueOf(userId));
        ack.acknowledge();
    }

    //扣减余额
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_MINUS)
    public void minus(String orderNo, Acknowledgment ack) {
        if (StringUtils.isBlank(orderNo)) {
            ack.acknowledge();
            return;
        }
        userAccountService.reduceAccount(orderNo);
        ack.acknowledge();
    }


    //出现异常时解锁余额
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_UNLOCK)
    public void unlock(String orderNo, Acknowledgment ack) {
        if (StringUtils.isBlank(orderNo)) {
            ack.acknowledge();
            return;
        }
        userAccountService.unlock(orderNo);
        ack.acknowledge();
    }

    @KafkaListener(topics = KafkaConstant.QUEUE_ORDER_PAY_SUCCESS)
    public void rechargePaySuccess(String orderNo,Acknowledgment ack){
        if (StringUtils.isBlank(orderNo)) {
            ack.acknowledge();
            return;
        }
        this.rechargeInfoService.updateRechargeInfo(orderNo);
        ack.acknowledge();
    }
}
